package com.byit.jwt.lifecycle;

import com.alibaba.fastjson.JSONObject;
import com.byit.enums.PromptInfo;
import com.byit.jwt.domain.JwtSession;
import com.byit.jwt.utils.JWTUtil;
import com.byit.msg.MessageResult;
import com.byit.utils.RedisUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * JwtSession 生命周期控制
 *
 * @author marker
 **/

@Aspect
public class JwtSessionLifecycleAspect {


    public static final String KEY = "jwt:session:";

    /**
     * Redis操作模板
     */
    @Autowired
    private RedisUtil redisUtil;


    /**
     * 连接点
     */
    @Pointcut("@annotation( com.byit.jwt.ann.JwtSessionController)")
    public void pointcutName() {
    }


    /**
     * 对某个方法返回的结果进行处理后，如将entity转换为与前端交互的vo
     */
    @Around(value = "pointcutName()")
    public Object aroundProcess(ProceedingJoinPoint pjp) throws Throwable {
        Object[] args = pjp.getArgs();
        MessageResult messageResult = (MessageResult) pjp.proceed(args);
        String resultCode = messageResult.getCode();
        String seccussCode = PromptInfo.SYS_SECCUSS.getCode();
        if (seccussCode.equals(resultCode)) {
            JSONObject data = (JSONObject) messageResult.getData();
            JwtSession session = JWTUtil.getSession(data.getString("token"));
            if (session != null) {
                Long memberId = session.userId();
                // 获取系统配置的时间
                long timeOut = 30 * 24 * 60 * 60L;
                // 直接更新
                redisUtil.set(KEY + memberId, data.getString("token"), timeOut);
            } else {
                return MessageResult.warpper(PromptInfo.SERVER_BUSY);
            }
        }
        return messageResult;
    }
}
